//订单确认页2018.9.12 湫创建  重构订单确认页
//默认初始华数据
// 转换时间戳
// top.Example(123);
function timeStamp2String(time,type) {
    let datetime = new Date(time);
    // datetime.setTime(time);
    let year = datetime.getFullYear();
    let month = datetime.getMonth() + 1;
    month = month < 10 ? ('0' + month) : month;
    let newDate = datetime.getDate();
    newDate = newDate < 10 ? ('0' + newDate) : newDate;
    let hour = datetime.getHours();
    hour = hour < 10 ? ('0' + hour) : hour;
    let minute = datetime.getMinutes();
    minute = minute < 10 ? ('0' + minute) : minute;
    let second = datetime.getSeconds();
    second = second < 10 ? ('0' + second) : second;
    if(type==1){
        return  hour;
    }if(type==2){
        return year + "年" + month + "月" + newDate+"日";
    }else {
        return year + "-" + month + "-" + newDate + " " + hour + ":" + minute + ":" + second;
    }
}
// console.log( JSON.parse(sessionStorage.getItem("customerInfo")));
var datalist = JSON.parse(sessionStorage.getItem("customerInfo"));
var nkm=  {skuModelList:[
        {
            "boxRowId":"1",
            "skuCode":"91001222001",
            "buyyerCount":"1",
            "salePrice":"530.00",
            "spuId":"1222",
            "skuId":"38030"
        },
        {
            "boxRowId":"2",
            "skuCode":"91002220002",
            "buyyerCount":"1",
            "salePrice":"28.90",
            "spuId":"2220",
            "skuId":"1108"
        }

    ],}
// console.log(nkm)
//客户信息
var customerInfo=JSON.parse(sessionStorage.getItem("customerInfo"));
var addressInfo={};
var deliverThird={
    private:'鑫方盛物流',
    kd:'快递',
    ky:'快运',
    kyMy:'快运',
    car:'专车包车',
}
function anskn(tuen) {
    switch (tuen) {
        case '鑫方盛物流':
            return 'private';
        case '快递':
            return 'kd';
        case '快运':
            return 'ky';
        case '快运':
            return 'kyMy';
        case '专车包车':
            return 'car';
    }
}
//提交需要参数
var streetId = '';
if(datalist.streetCode && datalist.streetCode!='' && datalist.streetCode!=0){
    streetId=datalist.streetCode;
    datalist.filterAreaCode =  datalist.streetCode;
}else if(datalist.districtCode && datalist.districtCode!='' && datalist.districtCode!=0){
    streetId=datalist.districtCode;
    datalist.filterAreaCode =  datalist.districtCode;
}else{
    streetId=datalist.cityCode;
    datalist.filterAreaCode =  datalist.cityCode;
}
var subdata={
    account_type:datalist.accountType,
    cityId:datalist.cityId,
    customerCode:datalist.customerCode,
    customerId:datalist.customerId,
    deliverWay:'',//当前选择配送方式
    device_platform:'apc',
    freightSeparate:'',//
    memberId:datalist.memberId,
    member_id:datalist.memberId,
    orderRemarks:'',
    optId:40,//
    timestamp:'',//当前时间
    warehouseId:datalist.warehouseId,
    skuModelList:datalist.skuModelList,//商品信息集合
    payModelChoosen:{
        payName:'',
        payType:''
    },//支付方式
    shippingAddressModel:chooseAddressObj,//地址信息集合
    couponChoosen:couponModel,//优惠劵信息集合
    payModel:{},
    filterAreaCode:streetId
}

var Subsubdata={
    account_type:datalist.accountType,
    cityId:datalist.cityId,
    customerCode:datalist.customerCode,
    customerId:datalist.customerId,
    deliverWay:'',//当前选择配送方式
    device_platform:'apc',
    freightSeparate:'',//
    memberId:datalist.memberId,
    member_id:datalist.memberId,
    orderRemarks:'',
    optId:40,//
    timestamp:'',//当前时间
    warehouseId:datalist.warehouseId,
    payModelChoosen:{
        payName:'',
        payType:''
    },//支付方式
    shippingAddressModel:chooseAddressObj,//地址信息集合
    couponChoosen:couponModel,//优惠劵信息集合
    dispatchBillModel:{
        skuModelList:{}
    },
    payModel:{}
}

var chooseShopId = '';//记录选中的收货地址
var chooseAddressObj = {};
var couponModel={}//记录选中优惠券数据
var databox={}//数据
var deliverSupport=[]
var freightdata=''//运费
var freightIsChange = '';//判断是否修改运费
var pricedata //是否改价
var Discount=true//判断改价状态
var coupon=''//优惠券减免
var yunupn=''//运费减免
var Totalcommodity='' //商品总额
/* 提交修改运费 */
var modifiyFreightReason=''
var couponModels=null
//判断临采商品
var Facetoface=false
var tempPurchase=0
for(var m=0; m<customerInfo.skuModelList[666].length; m++){
    if(customerInfo.skuModelList[666][m].spuId==0){
        Facetoface=true
        tempPurchase=1
    }
}
//初始化页面内容
defaer()
function defaer() {
    // console.log(888888)
    // console.log(JSON.stringify(datalist));
    web.doAjax(root.replaceInter.confirm, 'post',datalist, function (data) {
        if(data.errorCode==0){

        }else  if(data.errorCode==61){
            $("#noStock").modal("show");
        }else{
            if(data.abnormalProducts!=''||data.abnormalProducts!=undefined){
                $.Huimodalalert("商品有误请返回修改商品", 2000);
            }else {
                $.Huimodalalert(data.tip, 2000);
            }

        }
        databox=data;
        addressInit(databox.shoppingAddList)//地址
        method(databox.payModelList)//支付方式
        Distribution()
        commodity()//商品渲染
        renderCoupon()//优惠券
        pricedata=true
        $('#changeprice').val('商品改价')
    },1)
}
// -----------------------------地址列表的渲染
function addressInit(parame){
    // console.log(parame)
    $("#addressInfo").html('');

    if(parame && parame.length>0){  //Unfold
        $(".address_no").hide();
        $(".address_yes").show();
        var addressList = parame;
        var optionstring = "";
        for (var i = 0; i < addressList.length; i++){
            if (addressList.length < 2){ //展示全部按钮
                $(".Unfold").hide();
            }else{
                $(".Unfold").show();
            }
            var obj = addressList[i];
            var streetName = '';
            if (obj.street_id == 0) {
                obj.streetName = streetName;
            }
            var nameList = "";
            var nameLister=''
            var moblieList = "";
            var mobile = ''
            var PersonList = obj.addressPersonList;
            if (PersonList != null && PersonList.length > 0) {
                for (var j = 0; j < PersonList.length; j++){
                    if(j<=1){
                        nameList += PersonList[j].receiverName +' ';//姓名拼接
                        if(j==0){
                            // mobile = PersonList[j].mobile.substr(0,3) + "XXXX" + PersonList[j].mobile.substr(7);    //铭文显示手机号
                            mobile=PersonList[j].mobile
                        }
                    }else{
                        if(j==2){
                            nameList+='...';
                        }
                    }
                    nameLister+=PersonList[j].receiverName+ ' '+PersonList[j].mobile+ ' '
                }
            }
            var classChoose = '';
            var isDef = '';
            var isLimit='';
            if(chooseShopId>0 && chooseShopId == obj.ship_add_id){
                classChoose = 'addressSelected';
            };
            if(obj.is_default==1){
                isDef= '<i class="def_address">默认地址</i>';
            }

            if(obj.limitLine==10){
                isLimit= '<i class="limit_address">限行区域</i>';
            }
            if(addressList[i].add_alias==databox.shippingAddressModel.add_alias){
                if(chooseShopId == '') {
                    classChoose = 'addressSelected';
                    chooseShopId = obj.ship_add_id;
                    chooseAddressObj = obj;
                }
            }

            var detail = '';
            detail+=obj.provinceName;
            detail+=obj.cityName;
            if(obj.areaName){
                detail+=obj.areaName;
            }
            optionstring +='<div class="mb-5 ml-20 '+classChoose+'" style="float: left;position: relative; height: 30px;width: 90%;">'+
                '<span class="hide addressname">' + obj.add_alias + '</span>'+
                '<span class="hidden use_name_str">' + linkman + '</span>'+
                '<span class="address_name" title="'+nameLister+'" onclick="selectAddress(this,'+obj.ship_add_id+','+i+')" style="text-align: center;">' + nameList + '　　' + obj.provinceName + '</span>'+
                '<span class="address_detail">' + detail + obj.streetName + obj.detail_address + '</span>'+
                '<span class="user_phone">'+mobile+'</span>'+
                '<span>'+isDef+'</span>'+
                '<span>'+isLimit+'</span>'+
                '<span class="hide ship_add_id">' + obj.ship_add_id + '</span>'+
                ' <span style="margin-right:47px; float:right">'+
                '<a onclick="EditAddress('+obj.ship_add_id+')" >编辑</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+
                '<a onclick="DeleteAddress('+obj.ship_add_id+')" >删除</a>'+
                '</span>'+
                '</div>';
        }
        $("#addressInfo").html(optionstring);
        $("#addressInfo").prepend($("#addressInfo").find($(".addressSelected")));
    }else{
        $(".Unfold").hide();
        $(".address_no").show();
    }
}
// 选择地址
function selectAddress(el,id,obj){
    defaultTime=false
    chooseShopId = id;
    $(el).parent().addClass("addressSelected").siblings().removeClass("addressSelected");
    $("#addressInfo").prepend($("#addressInfo").find($(".addressSelected")));
    // for(var i=0;i<addressList.length;i++){
    //     if(addressList[i].ship_add_id == id){
    //         chooseAddressObj = addressList[i];
    //         return false;
    //     }
    // }
    //点击获取当前数据装入对象中
    var addressList = databox.shoppingAddList;
    for (var i = 0; i < addressList.length; i++) {
        var conmadta = addressList[obj];
        chooseAddressObj = conmadta;
    }
    console.log(chooseAddressObj)
    Submission()//保存当前数据
}
//删除地址
function DeleteAddress(ship_add_id) {
    console.log("ship_add_id=" + $("#ship_add_id").html());
    data = {
        shipAddId: ship_add_id,
        memberId:customerInfo.memberId
    };
    var succCallBack = function (data, status, response) {
        if (data.errorCode == 1) {
            $.Huimodalalert('删除地址成功', 2000);
            chooseAddressObj=null
            Submission();//刷新地址列表
        }
    };
    web.doAjax(root.replaceInter.replace_deleteMemberShoppingAddress, 'post', data, succCallBack);
}
//展开地址
function moreAddress() {
    $(".address_info").addClass("address_info_down");
    $("#more").attr("class", "hidden");
    $("#less").attr("class", "lessAdd");
}
//收起地址
function lessAddress() {
    // $('.address_info').scrollTop = document.documentElement.scrollTop = 0;
    document.getElementsByClassName('address_info')[0].scrollTo(0,0);
    $(".address_info").removeClass("address_info_down");
    $("#less").attr("class", "hidden");
    $("#more").attr("class", "lessAdd");

}

//添加地址弹框
function addAddress() {
    console.log("进入添加地址弹框");
    $("#dizhi").modal("show");
    $(".addressTitle").html("新增收货地址");
    addlink = "";
    addmobile = "";
    $("#linkman").empty();
    $("#tableid tbody").empty();
    $("#a").empty();
    $("#b").empty();
    // 查询收货人
    data = {
        customerCode: customerInfo.customerCode
    }
    $("#provinceName").html(customerInfo.provinceName);
    $("#cityName").html(customerInfo.cityName);
    $("#countyName").html(customerInfo.districtName);
    $("#villageName").html(customerInfo.streetName);
    $("#provinceId").html(customerInfo.provinceId);
    $("#cityId").html(customerInfo.cityId);
    $("#countyId").html(customerInfo.districtId);
    $("#villageId").html(customerInfo.streetId);
    $(".addAlias").val("");
    $(".detailedAddress").val("");
    $("#linkman").val("");
    $("#mobilephone").val("");
    $("#landlineCelephone").val("");
    isSave = 2;
}
/*保存收货地址*/
function saveAddress(){
    var arr = [];
    $('#tableid tbody tr').each(function (i, dom){
        arr.push({
            "name": $(dom).find('.consigneename').find('i').text(),
            "mobile": $(dom).find('.consigneetelephone').find('i').text() == "---" ? "" : $(dom).find('.consigneetelephone').find('i').text(),
            // "receiverId": $(dom).find('.consignee_id').text().length>0 ? $(dom).find('.consignee_id').text() : 0,
            'receiverId':0,
            "id": 0,
            "status": $(dom).find('.consignee_status').text().length>0 ? $(dom).find('.consignee_status').text() : 10,
            "addressId": 0,
        });
    });
    console.log(arr)
    if(arr.length<=0 && $("#linkman").length>0 && $("#mobilephone").length>0){
        arr.push({
            "name": $("#linkman").val(),
            "mobile": $("#mobilephone").val(),
            'receiverId':0,
            "id": 0,
            "status": 10,
            "addressId": 0,
        });
    }
    var address_data = {
        provinceId: customerInfo.provinceId,
        cityId: customerInfo.cityId,
        districtId: customerInfo.districtId,
        streetId: customerInfo.streetId,
        detailAddress: $("#detailedAddress").val(),
        addAlias: $("#addAlias").val(),
        officePhone: $("#landlineCelephone").val(),
        email: $("#email").val(),
        memberId: customerInfo.memberId,
        shipAddPersonJson: JSON.stringify(arr),
        cityCode:customerInfo.cityCode,
        districtCode:customerInfo.districtCode,
        member_id:customerInfo.member_id,
    };


    if (isSave == 1){ //编辑地址保存 

        address_data.provinceId = addressInfo.provinceId;
        address_data.cityId =addressInfo.cityId;
        address_data.districtId = addressInfo.districtId;
        address_data.streetId = addressInfo.streetId;
        address_data.districtCode = addressInfo.districtCode;
        address_data.cityCode =  addressInfo.cityCode;
        address_data.shipAddId = $("#dizhi").attr("data-shopid");

        console.log('编辑提交')
        console.log(address_data);

        var succCallBack = function (data, status, response){
            $("#dizhi").attr("data-shopid",'');
            if (data.errorCode == "0") {
                $.Huimodalalert('编辑地址成功', 2000);
                Submission();//刷新地址列表
                $("#dizhi").modal("hide");
                close_model()
            } else if (data.errorCode == "308") {
                isIng = false;
                $("#a").html('该授权收货人无效，请重新选择');
            } else if (data.errorCode == "302") {
                isIng = false;
                $("#b").html('收货人手机号重复，请重新选择');
            } else {
                $.Huimodalalert(data.errorMessage, 2000);
            }
        };
        web.doAjax(root.replaceInter.replace_adminUpdateMemberShoppingAddress, 'post', address_data, succCallBack);
    } else if (isSave == 2) {//添加新地址保存
        var succCallBack = function (data, status, response) {
            if (data.errorCode == "0") {
                $.Huimodalalert('添加地址成功', 2000);
                Submission();//刷新地址列表
                $("#dizhi").modal("hide");
                close_model()
            } else if (data.errorCode == "308") {
                isIng = false;
                $("#a").html('授权收货人无效授权收货人，请重新选择');

            } else if (data.errorCode == "302") {
                isIng = false;
                $("#c").html('手机号不能重复');
            } else {
                $.Huimodalalert(data.errorMessage, 2000);
            }
        };
        web.doAjax(root.replaceInter.replace_adminAddMemberShoppingAddress, 'post', address_data, succCallBack);
    }


}
var isSave; // 1 ==> 是修改地址   2 ==> 是添加地址
//编辑地址弹框
function EditAddress(addressBox) {
    //每次进来先清空一下
    $("#consigneename").val("");
    $("#consigneetelephone").val("");
    $('#linkman').val('')
    $('#mobilephone').val('')
    var handStr = "";
    $("#dizhi").modal("show");
    $("#dizhi").attr("data-shopid",addressBox);
    $(".addressTitle").html("编辑收货地址");
    var linkman = "";
    var moblie = "";
    $("#a").empty();
    $("#b").empty();
    var firstnameId;
    var secondnameId;
    // 查看地址信息
    data = {
        shipAddId: addressBox,
        memberId: customerInfo.memberId
    };
    var succCallBack = function (data, status, response){
        console.log('编辑地址');
        console.log(JSON.stringify(data.shippingAddress));
        if (data.errorCode == "1"){
            if (null != data.shippingAddress) {
                var ahipAdd = data.shippingAddress;
                var addressPersonArr = ahipAdd.addressPersonList;
                $("#addAlias").val(ahipAdd.add_alias);
                $("#detailedAddress").val(ahipAdd.detail_address);
                //分销客户禁止修改详细地址
                if(ahipAdd.address_type==10){
                    $("#detailedAddress").attr("disabled","disabled");
                }
                $("#landlineCelephone").val(ahipAdd.office_phone);
                $("#email").val(ahipAdd.email);
                if (addressPersonArr.length > 0){
                    for (var i = 0; i < addressPersonArr.length; i++){
                        handStr += '<tr style="margin-left: 30px">';
                        handStr += '<td style="text-align: left;padding-left:10px;width: 250px;"><span class="consigneename" style="display:inline-block;margin-left:45px;">姓名:<i>' + addressPersonArr[i].receiver_name + '</i></span></td>';
                        handStr += '<td style="text-align: left;padding-left: 5px;width: 186px;"><span style="text-align: left;display:block;" class="consigneetelephone">手机号码:<i>' + addressPersonArr[i].mobile + '</i></span></td>';
                        handStr += '<td><span class="consignee_id hide" >'+addressPersonArr[i].receiver_id+'</span></td>';
                        // handStr += '<td class="biaoge1-2"><span id="authorized_consignee_id" class="hide" >' + json[i].authorized_consignee_id + '</span></td>';
                        handStr += '<td><span class="consignee_status hide">'+addressPersonArr[i].status+'</span></td>';
                        // handStr += '<td class="biaoge1-2"><span id="ship_add_id" class="hide" >' + $("#ship_add_id") + '</span></td>';
                        handStr += '<td style="padding-left: 22px;"  onclick="Deletelinkman(this)"><a  href="javascript:;">删除</a></td>';

                        if(addressPersonArr[i].status !=10){
                            handStr += '<td style="padding-left: 22px;"><span>手机授权收货人无效，请重新选择</span></td>';
                        }else{
                            handStr += '<td style="padding-left: 22px;"><span></span></td>';
                        }
                        handStr += '</tr>';
                    }
                    $("#tableid").find("tbody").html(handStr);
                    handStr="";
                }
                addressInfo.provinceId = ahipAdd.province_id;
                addressInfo.cityId = ahipAdd.city_id;
                addressInfo.districtId = ahipAdd.district_id;
                addressInfo.streetId = ahipAdd.street_id;
                addressInfo.districtCode = ahipAdd.district_code;
                addressInfo.cityCode = ahipAdd.city_code;

                $("#provinceName").html(ahipAdd.provinceName);
                $("#cityName").html(ahipAdd.cityName);
                $("#countyName").html(ahipAdd.areaName);
                $("#villageName").html(ahipAdd.streetName);
                $("#provinceId").html(ahipAdd.province_id);
                $("#cityId").html(ahipAdd.city_id);
                $("#countyId").html(ahipAdd.district_code);
                $("#villageId").html(ahipAdd.street_id);

            }
        }
    };
    //修改地址时获取默认值
    web.doAjax(root.replaceInter.replace_adminViewMemberShipPerson, 'post', data, succCallBack);


    isSave = 1;
    return false;
}

//添加收货人名字和手机号
function addlinkman(id, ce){
    var addlink = $("#linkman").val();
    var addmobile = $("#mobilephone").val();
    var consigneeId = $("#consigneeId").val();
    var reg = /^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147)|(145)|(166))\d{8}$/;

    if(addlink.replace(/^ +| +$/g,'')==''){
        $.Huimodalalert('收货人姓名不能为空', 2000);
    }

    var nameReg = /^[\u4E00-\u9FA5]{2,5}$/;
    if(!nameReg.test(addlink)){
        $.Huimodalalert('收货人姓名只能为2到5位的汉字', 2000);
        return false;
    }

    if (addlink.length <= 0){   //验证收货人姓名不能为空
        $.Huimodalalert('收货人姓名不能为空', 2000);
        return false;
    } else if (addlink.length == 1){
        $.Huimodalalert('收货人姓名最少为两位', 2000);
        return false;

    } else if (addlink.length > 5){
        $.Huimodalalert('收货人姓名最多为五位', 2000);
        return false;
    }
    if (addmobile.length > 0 && (addmobile.length < 11 || !reg.test(addmobile))) {
        $.Huimodalalert('收货人手机号格式不正确', 2000);
        return;
    }
    var isTr = checkName(addlink,addmobile);
    addmobile = addmobile.length>1 ? addmobile : '---';
    if (isTr == true && addlink != null && addlink != ''){
        var handStr = '';
        handStr += '<tr style="margin-left: 30px">';
        handStr += '<td style=" text-align: left;padding-left:10px;width: 250px;"><span class="consigneename" style="display:inline-block;margin-left:45px;">姓名:<i>' + addlink + '</i></span></td>';
        handStr += '<td style="text-align: left;padding-left: 5px;width: 186px;"><span style="text-align: left;display:block;" class="consigneetelephone">手机号码:<i>' + addmobile + '</i></span></td>';
        handStr += '<td><span class="consignee_id hide" >' + consigneeId + '</span></td>';
        handStr += '<td><span class="consignee_status hide"></span></td>';
        handStr += '<td style="padding-left: 22px;"  onclick="Deletelinkman(this)"><a  href="javascript:;">删除</a></td>';
        handStr += '<td style="padding-left: 22px;"><span></span></td>';
        handStr += '</tr>';
        $("#tableid").find("table>tbody").append(handStr);
        $("#linkman").val('');
        $("input[name=mobilephone]").val('');
        $("#consigneeId").val('');
    }
}
//校验添加的收货人名字和手机号
function checkName(name,mob) {
    var flag = true;
    var arr = [];
    $('#tableid tbody tr').each(function (i, dom){
        arr.push({
            "name": $(dom).find('.consigneename').text().split(":")[1],
            "mobile": $(dom).find('.consigneetelephone').text().split(":")[1] == "---" ? "" : $(dom).find('.consigneetelephone').text().split(":")[1],
        });
        console.log(arr);
        //手机号码和姓名不能重复
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].name == name) {
                $.Huimodalalert('该收货人已存在', 2000);
                console.log("该收货人已存在");
                flag = false;
            }
            if (mob.length > 0 && arr[i].mobile == mob) {
                $.Huimodalalert('该手机号码已存在', 2000);
                flag = false;
            }
        }
        if (arr.length >= 10) {
            $.Huimodalalert('最多可添加10个收货人', 2000);
            flag = false;
        }

    });
    return flag;
}
//删除授权收货人
function Deletelinkman(k) {
    $(k).parent().remove();
}
// -----------------------------------------------------地址管理

//-------------------------------------优惠券
function renderCoupon() {
    var data=databox
    var couponData = databox.couponSpuSkuBoList;
    if(!databox.couponChoosen){
        couponModels=null
        yunupn=0.00
        coupon=0.00
        bootmonry()
    }
    if(couponData==''){
        $('#couponDataHtnl').hide()
    }
    var couponStr = "";
    if (couponData == undefined) {
        couponModel = null;
        couponModels=null
    } else {
        for (var i = 0; i < couponData.length; i++) {
            var endTime = (couponData[i].useEndtime).slice(0, 10);
            var manHtml=''
            var coaler=''
            var backbor=''
            if(couponData[i].couponType=='10'){
                manHtml='<span class="mandelsin">满减券</span>'
                coaler='beijing3'
                backbor='beijing3down'

            }else {
                manHtml='<span class="mandelsin">运费券</span>'
                coaler='yunbeijing3'
                backbor='yunbeijing3down'
            }
            //默认选中状态
            var mission=''
            if (data.couponChoosen){
                mission=data.couponChoosen.couponCode
            }

            if (mission == couponData[i].couponCode) {
                couponStr += '<div class="coupon_list_box on_uncheck" onclick="chooseCoupon(this,' + i + ')">'
                    + '<div class="Uncheck uncheak1" style="display: block;"  onclick="cancelChoose(this,event,' + i + ')">取消勾选</div>'
                    + '<div class="'+coaler+'" >'
                    + '<div class="money" style="display: inline-block;">¥<span style="float: none;margin-right: 0" id="DiscountedPrice">' + couponData[i].couponValue + '</span></div>'
                    + '<div class="useConditions" style="display: inline-block;">满' + couponData[i].couponUseCondition + '使用</div>'
                    + '<div class="Validityperiod">有效期至' + endTime + '</div></div>'
                    + '<div class="'+backbor+'" ><span>[限平台限品类]</span>' + manHtml + '<span id="couponCode" class="hide">' + couponData[i].couponCode + '</span></div>'
                    + '</div>';
                // $("#youhuijuan").html(Number(data.couponOffset).toFixed(2));
                if (couponData[i].couponValue >= data.goodTotalMoney) {
                    /*优惠券拼装*/
                    couponModel = {
                        "couponCode": couponData[i].couponCode,//优惠券编码
                        "couponDesc": couponData[i].couponDesc,//"优惠券描述",
                        "couponRealValue": couponData[i].couponRealValue,//优惠券实际金额  满多少
                        "couponScope": couponData[i].couponScope,//优惠券适用范围
                        "couponSkuModelList": couponData[i].spuSkuBoList,//优惠券使用商品列表
                        "couponType": couponData[i].couponType,//优惠券类型
                        "couponOffsetValue": couponData[i].couponValue,//优惠券可以抵扣的金额(原优惠券配置的可以抵用的金额)
                        "couponValue": data.goodTotalMoney,//优惠券 抵用的金额 实际使用的金额(若商品金额小于抵用金额,取商品金额)
                    }
                    couponModels=couponModel
                } else {
                    /*优惠券拼装*/
                    couponModel = {
                        "couponCode": couponData[i].couponCode,//优惠券编码
                        "couponDesc": couponData[i].couponDesc,//"优惠券描述",
                        "couponRealValue": couponData[i].couponRealValue,//优惠券实际金额  满多少
                        "couponScope": couponData[i].couponScope,//优惠券适用范围
                        "couponSkuModelList": couponData[i].spuSkuBoList,//优惠券使用商品列表
                        "couponType": couponData[i].couponType,//优惠券类型
                        "couponOffsetValue": couponData[i].couponValue,//优惠券可以抵扣的金额(原优惠券配置的可以抵用的金额)
                        "couponValue": couponData[i].couponValue,//优惠券 抵用的金额 实际使用的金额(若商品金额小于抵用金额,取商品金额)
                    }
                    couponModels=couponModel
                }
                if(couponData[i].couponType=='10'){
                    coupon = couponData[i].couponValue
                    yunupn=0.00
                }else {
                    yunupn=couponData[i].couponValue
                    coupon=0.00
                }
                bootmonry()
            } else {
                if (couponData[i].couponUseStatus == 0) {
                    couponStr += '<div class="coupon_list_box" onclick="chooseCoupon(this,' + i + ')"><div class="Uncheck uncheak1" onclick="cancelChoose(this,event,' + i + ')" >取消勾选</div>'
                        + '<div class="'+coaler+'"><div class="money" style="display: inline-block;">¥<span style="float: none;margin-right: 0" id="DiscountedPrice">' + couponData[i].couponValue + '</span></div>'
                        + '<div class="useConditions" style="display: inline-block;">满' + couponData[i].couponUseCondition + '使用</div>'
                        + '<div class="Validityperiod">有效期至' + endTime + '</div></div>'
                        + '<div class="'+backbor+'" >'
                        + '<span>[限平台限品类]</span>' + manHtml + '<span id="couponCode" class="hide">' + couponData[i].couponCode + '</span>'
                        + '</div></div>';
                } else {
                    //不可用
                    couponStr += '<div class="coupon_list_box"><div class="beijing5" style="float: none;">'
                        + '<div class="money" style="display: inline-block;">¥' + couponData[i].couponValue + '</div>'
                        + '<div class="useConditions" style="display: inline-block;">满' + couponData[i].couponUseCondition + '使用</div><div class="Validityperiod">有效期至' + endTime + '</div></div>'
                        + '<div class="beijing5down">[限平台限品类]' + manHtml + '</div><span id="couponCode" class="hide">' + couponData[i].couponCode + '</span>'
                        + '</div>';
                }
            }
        }
        $("#beijing1").html(couponStr);
        // '<div class="beijing3_info">金额抵用<span class="yhq_text" id="actualVal">' + Number(data.couponRealValue).toFixed(2) + '</span>优惠券<span id="couponNum">1</span>张</div>'
    }
}
/*选择优惠券*/
function chooseCoupon(el,coomer) {
    if(Discount){
        console.log(coomer)
        var ier=Number(coomer)
        couponData=databox.couponSpuSkuBoList
        // for (var i = 0; i < couponData.length; i++) {
        couponModel = {
            "couponCode": couponData[ier].couponCode,//优惠券编码
            "couponDesc": couponData[ier].couponDesc,//"优惠券描述",
            "couponRealValue": couponData[ier].couponRealValue,//优惠券实际金额  满多少
            "couponScope": couponData[ier].couponScope,//优惠券适用范围
            "couponSkuModelList": couponData[ier].spuSkuBoList,//优惠券使用商品列表
            "couponType": couponData[ier].couponType,//优惠券类型
            "couponOffsetValue": couponData[ier].couponValue,//优惠券可以抵扣的金额(原优惠券配置的可以抵用的金额)
            // "couponValue": data.goodTotalMoney,//优惠券 抵用的金额 实际使用的金额(若商品金额小于抵用金额,取商品金额)
        }
        couponModels=couponModel
        console.log(couponModel)
        // }
        $("#yunfei-afterChange").html("");//清空运费
        $("#afterFare-remark").html("");//清空缓存
        $(".uncheak1").css("display", "none");
        $(el).addClass("on_uncheck");
        for (var i = 0; i < $(el).siblings().length + 1; i++) {
            $($(el).siblings()[i]).removeClass("on_uncheck");
        }
        $(el).find(".uncheak1").css("display", "block");
        var Discountedprice = $("#DiscountedPrice").html(); //优惠券抵扣金额
        var AmountGoods = $(".good_total_price").html(); //商品总额
        // if (!freightIsChange) {
        //     calculateFare(Number(Discountedprice), Number(AmountGoods));//运费计算
        // }
        // if (Number(Discountedprice) >= Number(AmountGoods)) {
        //     $("#youhuijuan").html(Number(AmountGoods).toFixed(2));
        //     $("#zongjine").html(Number($("#yunfei").html()).toFixed(2));
        //     $("#couponNum").html(1);
        //     $("#actualVal").html(Number(AmountGoods).toFixed(2));
        // } else {
        //     $("#youhuijuan").html(Number(Discountedprice).toFixed(2));
        //     $("#zongjine").html((Number($("#yunfei").html()) + Number(AmountGoods) - Number(Discountedprice)).toFixed(2));
        //     $("#couponNum").html(1);
        //     $("#actualVal").html(Number(Discountedprice).toFixed(2));
        // }
        if(couponModel.couponType=='10'){
            coupon=couponModel.couponRealValue
            yunupn=0.00
        }else {
            yunupn=couponModel.couponRealValue
            coupon=0.00
        }
        bootmonry()
        Submission()
    }else {
        layer.msg('改价无法使用优惠券', {icon: 5, time: 2000});
    }
}
/*取消选择优惠券*/
function cancelChoose(el, e,me) {
    e.stopPropagation();   //组织冒泡
    $("#yunfei-afterChange").html("");//清空运费
    $("#afterFare-remark").html("");//清空缓存
    $(el.parentElement).removeClass("on_uncheck");
    $(el).css("display", "none");
    couponModel = {
        "couponCode": 0,//优惠券编码
        "couponDesc": databox.couponSpuSkuBoList[me].couponDesc,//"优惠券描述",
        "couponRealValue": databox.couponSpuSkuBoList[me].couponRealValue,//优惠券实际金额  满多少
        "couponScope": databox.couponSpuSkuBoList[me].couponScope,//优惠券适用范围
        "couponSkuModelList": databox.couponSpuSkuBoList[me].spuSkuBoList,//优惠券使用商品列表
        "couponType": databox.couponSpuSkuBoList[me].couponType,//优惠券类型
        "couponOffsetValue": databox.couponSpuSkuBoList[me].couponValue,//优惠券可以抵扣的金额(原优惠券配置的可以抵用的金额)
        "couponValue": databox.couponSpuSkuBoList[me].couponValue,//优惠券 抵用的金额 实际使用的金额(若商品金额小于抵用金额,取商品金额)
    }
    couponModels=null
    console.log(couponModel)
    coupon=0.00
    yunupn=0.00
    bootmonry(1)
    Submission()
}
//----------------------------------------------优惠券
//----------------------------------------------发票
var invoiceInfo={};   //发票信息
getInvoiceInfo();//初始化发票信息
function getInvoiceInfo(param) {
    $.ajax({
        url: root.replaceInter.queryInvoiceInfoByMemberId,
        cache: false, //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/x-www-form-urlencoded",
        data: param||{memberId:customerInfo.memberId,invoiceType:'10'},
        success: function (data) {
            // console.log(data)
            if(param && param.invoiceType==10){
                $('#increase').val(data.data.company_name);
                $('#taxpayerCode').val(data.data.taxpayer_code);
            } else if(param && param.invoiceType==20){
                $('#name').val(data.data.company_name);
                $('#code').val(data.data.taxpayer_code);
                $('#phone').val(data.data.reg_telephone);
                $('#address').val(data.data.reg_address);
                $('#bank').val(data.data.open_account_bank);
                $('#bankNumber').val(data.data.bank_account);
            } else{
                $('#increase').val(data.data.company_name);
                $('#taxpayerCode').val(data.data.taxpayer_code);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}
function invoice_change(){
    $("#modal-demoOne").modal("show");
    var succCallBack = function(data){
        console.log(data);
        customerInfo.accountType = data.list[0].account_type;
        console.log(customerInfo);
        if (customerInfo.accountType==20){
            document.getElementById("check_value").disabled=true;
        } else {
            document.getElementById("check_value").disabled=false;
        }
    }
    web.doAjax(root.replaceInter.replace_adminQueryCustomerNameOrAccount, 'post', {
        loginAccount:customerInfo.customerLoginAccount
    }, succCallBack);
}
//新増单位发票
var invoiceType=1;//1是普通发票；2是增值税发票
var normalInvoice=1;//1是个人普通发票；2是单位普通发票
function perOrCom(val){
    if (val==2){
        $("#increase").addClass("check_invoice");
        $("#per_invoice").removeClass("check_invoice");
        $("#unit_info").show();
    } else {
        $("#unit_info").hide();
        $("#per_invoice").addClass("check_invoice");
        $("#increase").removeClass("check_invoice");
    }
    normalInvoice = val;
}
var openFlag = false;
function change_invoice(val){
    invoiceType=val;
    if (val==1){
        $("#regular_invoice").show();
        $("#value_invoice").hide();
        $("#check_regular").addClass("check_invoice");
        $("#check_value").removeClass("check_invoice");
        getInvoiceInfo({memberId:customerInfo.memberId,invoiceType:'10'})
    } else {
        if (customerInfo.accountType==10){
            $("#value_invoice .input-text").prop("disabled","disabled");
        }
        $("#check_value").addClass("check_invoice");
        $("#check_regular").removeClass("check_invoice");
        $("#regular_invoice").hide();
        $("#value_invoice").show();
        getInvoiceInfo({memberId:customerInfo.memberId,invoiceType:'20'})
    }
}
function no_invoice() {
    openFlag=false;
    $("#no_invoice").addClass("check_invoice");
    $("#goods_info").removeClass("check_invoice")
}
function goods_info() {
    openFlag=true;
    $("#goods_info").addClass("check_invoice");
    $("#no_invoice").removeClass("check_invoice");
}
function saveInvoice() {  //保存发票信息
    var customerId = getQueryString('customerId');
    var id = getQueryString('id');
    var organizationName = $("#name").val();
    var taxpayerCode = $("#code").val();
    var registeredAddress = $("#address").val();
    var registeredPhone = $("#phone").val();
    var openingBank = $("#bank").val();
    var bankAccount = $("#bankNumber").val();
    if (invoiceType==2){
        if(organizationName == "") {
            layer.msg('请填写单位名称', {icon: 5, time: 2000});
            return false;
        }
        if(taxpayerCode == "") {
            layer.msg('请填写纳税人识别号', {icon: 5, time: 2000});
            return false;
        }
        // else{
        //     var sccess = checkedTaxpayerCode(taxpayerCode);
        //     if(!sccess){
        //         layer.msg('纳税人识别号格式错误', {icon: 5, time: 2000});
        //         return;
        //     }
        // }

        if(registeredAddress == "") {
            layer.msg('请填写注册地址', {icon: 5, time: 2000});
            return false;
        }

        if(registeredPhone == "") {
            layer.msg('请填写注册电话', {icon: 5, time: 2000});
            return false;
        }
        var mobile = /^1[3|5|8]\d{9}$/ , phone = /^0\d{2,3}-?\d{7,8}$/;
        if( !mobile.test(registeredPhone) && !phone.test(registeredPhone)){
            layer.msg('注册电话格式错误', {icon: 5, time: 2000});
            return false;
        }


        if(openingBank == "") {
            layer.msg('请填写开户银行', {icon: 5, time: 2000});
            return false;
        }

        if(bankAccount == "") {
            layer.msg('请填写银行帐号', {icon: 5, time: 2000});
            return false;
        }
        if(bankAccount.length < 16 || bankAccount.length > 30) {
            layer.msg('银行帐号长度必须在16到30之间', {icon: 5, time: 2000});
            return false;
        }
        var num = /^\d*$/; //全数字
        if(!num.exec(bankAccount)) {
            layer.msg('银行帐号必须全为数字', {icon: 5, time: 2000});
            return false;
        }
        //开头6位
        var strBin = "10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99";
        if(strBin.indexOf(bankAccount.substring(0, 2)) == -1) {
            layer.msg('银行帐号开头6位不符合规范', {icon: 5, time: 2000});
            return false;
        }
    } else {
        if (normalInvoice==2){
            if ($('#increase').val()==''){
                layer.msg('请填写单位发票抬头', {icon: 5, time: 2000});
                return false;
            }
            if ($('#taxpayerCode').val()==''){
                layer.msg('请填写纳税人识别码', {icon: 5, time: 2000});
                return false;
            }
        }
    }
    /*$.ajax({
        url: 'https://'+ window.location.host +'/api/admin/acontract/invoice/insertInvoice.jhtml',
        cache: false, //禁用缓存
        type: "POST",
        dataType: "json",
        data: {
            customerId: customerId,
            customerCode:id,
            organizationName:organizationName,
            taxpayerCode:taxpayerCode,
            registeredAddress:registeredAddress,
            registeredPhone:registeredPhone,
            openingBank:openingBank,
            bankAccount:bankAccount
        },
        success: function (obj) {
            if (obj.sub_code == 0) {
                layer.msg(obj.sub_msg, {
                    icon: 1,
                    time: 1000,
                });
            } else {
                layer.msg(obj.sub_msg, {icon: 5, time: 2000});
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });*/
    //发票信息
    if (invoiceType === 1) {
        if (normalInvoice === 1) {
            invoiceInfo = {
                invoiceType:invoiceType,
                normalInvoice:normalInvoice,
                title:"个人"
            }
            let saveParam = {

                "member_id":customerInfo.memberId,

                "invoice_type":10,

                "company_name":'',

                "taxpayer_code":'',

                "reg_address":'',

                "reg_telephone":'',

                "open_account_bank":'',

                "bank_account":''

            }
            saveAjax(saveParam)
        } else {
            let title = $("#increase").val()
            let code = $("#taxpayerCode").val()
            invoiceInfo = {
                invoiceType:invoiceType,
                normalInvoice:normalInvoice,
                title:title,
                code:code
            }
            let saveParam = {

                "member_id":customerInfo.memberId,

                "invoice_type":10,

                "company_name":title,

                "taxpayer_code":code,

                "reg_address":'',

                "reg_telephone":'',

                "open_account_bank":'',

                "bank_account":''

            }
            saveAjax(saveParam)
        }
    } else {
        console.log(invoiceType)
        let valInvoice = $(".invoiceInfo")
        invoiceInfo = {
            invoiceType:invoiceType,
            normalInvoice:normalInvoice,
            title:valInvoice[0].value,
            code:valInvoice[1].value,
            address:valInvoice[2].value,
            phone:valInvoice[3].value,
            bank:valInvoice[4].value,
            bankAccount:valInvoice[5].value
        };
        let saveParam = {

            "member_id":customerInfo.memberId,

            "invoice_type":20,

            "company_name":valInvoice[0].value,

            "taxpayer_code":valInvoice[1].value,

            "reg_address":valInvoice[2].value,

            "reg_telephone":valInvoice[3].value,

            "open_account_bank":valInvoice[4].value,

            "bank_account":valInvoice[5].value

        }
        saveAjax(saveParam)
    }
    console.log(invoiceInfo);
    if(invoiceInfo.invoiceType==2){
        openFlag = true;
    }
    if(invoiceInfo.invoiceType==1){
        if($("#goods_info").hasClass("check_invoice")){
            openFlag = true;
        }else{
            openFlag = false;
        }
    }
    if(openFlag){
        if(invoiceInfo.invoiceType==1){
            $('#invoiceModify').show()
            $('#invoiceText').text('普通发票   '+invoiceInfo.title)
        }
    }else {
        $('#invoiceModify').show()
        $('#invoiceText').text('不开发票')
    }
    if(invoiceInfo.invoiceType==2){

        $('#invoiceModify').show()
        $('#invoiceText').text('增值税专用发票   '+invoiceInfo.title)
    }
}
//保存发票信息
function saveAjax(param){
    $.ajax({
        url: root.replaceInter.saveInvoiceInfo,
        cache: false, //禁用缓存
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        /*   data: {
               customerId: customerId,
               customerCode:id,
               organizationName:organizationName,
               taxpayerCode:taxpayerCode,
               registeredAddress:registeredAddress,
               registeredPhone:registeredPhone,
               openingBank:openingBank,
               bankAccount:bankAccount
           },*/
        data: JSON.stringify(param),
        success: function (data) {
            console.log(data);
            console.log(invoiceInfo);
            $('#modal-demoOne').modal('hide');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}
//校验纳税人识别号
function checkedTaxpayerCode(taxpayerId){  //纳税人识别号校验是否合法
    if($.trim(taxpayerId) != ''){
        var addressCode = taxpayerId.substring(0,6);
        // 校验地址码
        var check = checkAddressCode(addressCode);
        if(!check) {
            layer.msg('请输入正确的纳税人识别号 (地址码)！', {icon: 5, time: 2000});
            return false;
        }else{
            // 校验组织机构代码
            var orgCode = taxpayerId.substring(6,9);
            check = orgcodevalidate(orgCode);
            if(!check){
                layer.msg('请输入正确的纳税人识别号 (组织机构代码)！', {icon: 5, time: 2000});
                return false;
            }
        }
        return true;
    }
    // 校验组织机构代码
    function orgcodevalidate(value){
        if(value!=""){
            var part1=value.substring(0,8);
            var part2=value.substring(value.length-1,1);
            var ws = [3, 7, 9, 10, 5, 8, 4, 2];
            var str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            var reg = /^([0-9A-Z]){8}$/;
            if (!reg.test(part1))
            {
                return true
            }
            var sum = 0;
            for (var i = 0; i< 8; i++)
            {
                sum += str.indexOf(part1.charAt(i)) * ws[i];
            }
            var C9 = 11 - (sum % 11);
            var YC9=part2+'';
            if (C9 == 11) {
                C9 = '0';
            } else if (C9 == 10) {
                C9 = 'X' ;
            } else {
                C9 = C9+'';
            }
            return YC9!=C9;
        }
    }

    // 校验地址码
    function checkAddressCode(addressCode){
        var provinceAndCitys={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",
            31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",
            45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",
            65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"};
        var check = /^[1-9]\d{5}$/.test(addressCode);
        if(!check) return false;
        if(provinceAndCitys[parseInt(addressCode.substring(0,2))]){
            return true;
        }else{
            return false;
        }

    }
}
//-----------------------------------------------------------------------------发票
//支付方式
function method(data){
    var optionstring=''
    $("#methodHtml").html('')
    for(var i=0; i<data.length; i++){
        var zhangHtml=''
        var zhangHtmlser=''
        var xiasnbg=''
        var TipsThtml=''
        if(data[i].payName=='货到付款'){
            if(data[i].onoff==-1){
                xiasnbg='prohibitocnk'
                TipsThtml=data[i].remark
            }
        }
        var shenp='不需要审批'
        if(customerInfo.neetAudit==10){
            shenp='需要审批'
        }
        if(databox.payModelChoosen.payType==data[i].payType){
            if(data[i].payName=='账期支付'){
                if(data[i].accountAvailable){
                    zhangHtml='<span style="position: absolute; top: 40px; right: 8px; width: 310px; text-align: center">'+shenp+'可用授信额度'+data[i].accountAvailable+'</span>'
                }else {
                    zhangHtml=''
                }
            }
            optionstring +='<span style="position: relative" title="'+TipsThtml+'" class="pattern_of_payment Selectexnt '+xiasnbg+'" onclick="change(this)" data-paySubType="'+data[i].paySubType+'" data-id="'+data[i].payType+'" data-text="'+data[i].payName+'">'+data[i].payName+''+zhangHtml+'</span>'
            modifyCurrent(''+data[i].payName+','+data[i].paySubType+'')
        }else{
            if(data[i].payName=='账期支付'){
                zhangHtmlser='<label style="display:none; position: absolute; top: 40px; right: 8px; width: 310px; text-align: center">'+shenp+'可用授信额度'+data[i].accountAvailable+'</label>'
            }else {
                zhangHtml=''
            }
            if(data[i].payName=='货到付款'){
                if(data[i].onoff==-1){
                    optionstring +='<span style="position: relative" title="'+TipsThtml+'" class="pattern_of_payment " data-paySubType="'+data[i].paySubType+'"  data-id="'+data[i].payType+'" data-text="'+data[i].payName+'">'+data[i].payName+''+zhangHtmlser+'</span>'
                }else {
                    optionstring +='<span style="position: relative" title="'+TipsThtml+'" class="pattern_of_payment "  onclick="change(this)" data-paySubType="'+data[i].paySubType+'"   data-id="'+data[i].payType+'" data-text="'+data[i].payName+'">'+data[i].payName+''+zhangHtmlser+'</span>'
                }
            }else {
                optionstring +='<span style="position: relative" title="'+TipsThtml+'" class="pattern_of_payment '+xiasnbg+'" onclick="change(this)" data-paySubType="'+data[i].paySubType+'"  data-id="'+data[i].payType+'" data-text="'+data[i].payName+'">'+data[i].payName+''+zhangHtmlser+'</span>'
            }

        }
    }
    $("#methodHtml").html(optionstring);
}
var paymentState=false
//选择支付方式操作
function change(me) {
    if(!$(me).hasClass('Selectexnt')){
        $(me).addClass('Selectexnt').siblings().removeClass('Selectexnt')
        if($(me).attr('data-text')=='账期支付'){
            $(me).children().show()
        }else {
            $(me).siblings().children().hide()
            // console.log($(me).siblings().children().hide())
        }
    }
    // invoiceInfo=null//发票信息
    var meHtml=$(me).attr('data-text')
    var paySubType=$(me).attr('data-paySubType')
    modifyCurrent(meHtml,paySubType)
}
var textlsn
function modifyCurrent(temt,lonwer) {
    if(customerInfo.accountType==10){
    }
    if(temt=='账期支付'){
        textlsn=$('#invoiceText').text()
        $('#invoiceModify').hide()
        $('#invoiceText').text('账期客户需在个人中心统一补开发票')
    }else {
        //  $('#invoiceModify').show()
        //  $('#invoiceText').text(textlsn)
        // textlsn=$('#invoiceText').text()
        if(openFlag){
            if(invoiceInfo.invoiceType==1){
                $('#invoiceModify').show()
                $('#invoiceText').text('普通发票   '+invoiceInfo.title)
            }
        }else {
            $('#invoiceModify').show()
            $('#invoiceText').text('不开发票')
        }
        if(invoiceInfo.invoiceType==2){

            $('#invoiceModify').show()
            $('#invoiceText').text('增值税专用发票   '+invoiceInfo.title)
        }
    }
    if(temt=='货到付款'){
        //三全合一账号显示此按钮
        // alert(lonwer)
        if(lonwer!='undefined'){
            $('#goodsArrived').show()
            paymentState=true
        }else {
            $('#goodsArrived').hide()
            paymentState=false
        }
    }else {
        $('#goodsArrived').hide()
    }
}
var Timeappdatan=[]
var Minutedatan=['08:00-12:00','12:00-17:00','17:00-22:00']
//初始选中传值
function ergodicdata(data,tep) {
    if(tep==1){
        for(var i=0; i<Timeappdatan.length; i++){
            console.log(Timeappdatan[i])
            if(Timeappdatan[i]==data){
                return i
            }
        }
    }else {
        for(var i=0; i<Minutedatan.length; i++){
            console.log(Minutedatan[i])
            if(Minutedatan[i]==data){
                return i
            }
        }
    }
}
//配送方式
function Distribution() {
    var quanhtml=''
    if(databox.deliverSupport){
        deliverSupport=databox.deliverSupport.split(",");//获取配送方式
        for(var i=0; i<deliverSupport.length; i++){
            if(Facetoface){
                var current=databox.deliverWay
                if(databox.deliverWay=='kyMy'){
                    current='ky'
                }
                //临采商品 询价单进入
                var textnKl=''
                if(deliverThird[deliverSupport[i]]=='鑫方盛物流'){
                    textnKl='配送订单'
                }else {
                    textnKl='外阜订单'
                }
                if(current==deliverSupport[i]){
                    var mran=''
                    if(databox.deliverWaySecondary==10){
                        mran='<label for="yes"><input type="radio" name="conernt" id="" value="0" >'+textnKl+'</label><label for="no"><input type="radio" name="conernt" id=""  checked="checked"  value="10" >厂家直发</label>'
                    } else if(databox.deliverWaySecondary==0){
                        mran='<label for="yes"><input type="radio" name="conernt" id="" checked="checked"  value="0" >'+textnKl+'</label><label for="no"><input type="radio" name="conernt" id=""  value="10" >厂家直发</label>'
                    }else {
                        mran='<label for="yes"><input type="radio" name="conernt" id="" value="0" >'+textnKl+'</label><label for="no"><input type="radio" name="conernt" id=""  value="10" >厂家直发</label>'
                    }
                    if(deliverThird[deliverSupport[i]]=='快运'){
                        var mranHtml=''
                        if(databox.deliverWay=='kyMy'){
                            //站点自提默认选中
                            mranHtml='<label for="yes"><input type="radio" onclick=" fastdata(1)" name="expressyun" id="" value="0" >送货上门</label><label for="no"><input onclick=" fastdata(2)" type="radio" name="expressyun" id=""   value="10" checked="checked" >站点自提</label>'
                            freight('kyMy')
                        }else {
                            //送货上门默认选中
                            mranHtml='<label for="yes"><input onclick="fastdata(1)" type="radio" name="expressyun" id="" value="0" checked="checked">送货上门</label>'+mran+'<label for="no"><input onclick=" fastdata(2)" type="radio" name="expressyun" id=""   value="10" >站点自提</label>'
                                // +''+mran+''
                            freight(anskn(deliverThird[deliverSupport[i]]))
                        }
                        quanhtml+=' <li class="cation" data-text="'+anskn(deliverThird[deliverSupport[i]])+'" onclick="butionchan(this)">'+deliverThird[deliverSupport[i]]+'</li>'
                            + '<li style="border: none">'+mranHtml+'</li>'
                    }else {
                        //除快运
                        quanhtml+=' <li data-text="'+anskn(deliverThird[deliverSupport[i]])+'" onclick="butionchan(this)" class="cation">'+deliverThird[deliverSupport[i]]+'</li>'
                            + '<li style="border: none">'+mran+'</li>'
                        freight(anskn(deliverThird[deliverSupport[i]]))
                    }
                }else {
                    quanhtml+=' <li data-text="'+anskn(deliverThird[deliverSupport[i]])+'" onclick="butionchan(this)">'+deliverThird[deliverSupport[i]]+'</li>'
                }
            }else {
                var current=databox.deliverWay
                if(databox.deliverWay=='kyMy'){
                    current='ky'
                }
                //快运逻辑
                if(current==deliverSupport[i]){
                    if(deliverThird[deliverSupport[i]]!='鑫方盛物流'){
                        $('#LimitlineNo').hide()
                        $('#Limitline').hide()
                        $('#morningAfternoon').hide()
                    }else {
                        $('#morningAfternoon').show()
                    }
                    if(deliverThird[deliverSupport[i]]=='快运'){
                        var mranHtml=''
                        if(databox.deliverWay=='kyMy'){
                            //站点自提默认选中
                            mranHtml='<label for="yes"><input type="radio" onclick=" fastdata(1)" name="expressyun" id="" value="0" >送货上门</label><label for="no"><input onclick=" fastdata(2)" type="radio" name="expressyun" id=""   value="10" checked="checked" >站点自提</label>'
                            freight('kyMy')
                        }else {
                            //送货上门默认选中
                            mranHtml='<label for="yes"><input onclick="fastdata(1)" type="radio" name="expressyun" id="" value="0" checked="checked">送货上门</label><label for="no"><input onclick=" fastdata(2)" type="radio" name="expressyun" id=""   value="10" >站点自提</label>'
                            freight(anskn(deliverThird[deliverSupport[i]]))
                        }
                        quanhtml+=' <li class="cation" data-text="'+anskn(deliverThird[deliverSupport[i]])+'" onclick="butionchan(this)">'+deliverThird[deliverSupport[i]]+'</li>'
                            + '<li style="border: none">'+mranHtml+'</li>'
                    }else {
                        //除快运
                        quanhtml+=' <li data-text="'+anskn(deliverThird[deliverSupport[i]])+'" onclick="butionchan(this)" class="cation">'+deliverThird[deliverSupport[i]]+'</li>'
                        freight(anskn(deliverThird[deliverSupport[i]]))
                        timeFun(anskn(deliverThird[deliverSupport[i]]))
                        // //选择期望配送时间
                        if(deliverThird[deliverSupport[i]]=='鑫方盛物流'){
                            if(!customerInfo.out_of_stock){//是否现货
                                if(databox.shippingAddressModel.areaLimitLine == 10){//是否限行
                                    // console.log('限行')
                                    $('#Limitline').show()
                                    var creatOrderHour = timeStamp2String(databox.serverTime, 1);
                                    if (creatOrderHour > 12){//超过中午12点
                                        $('#limitAtext').addClass('alery').text('预约已满')
                                    }
                                }else {
                                    // console.log('不限行')
                                    var creatOrderHour = timeStamp2String(databox.serverTime, 1);
                                    $('#LimitlineNo').show()
                                    if (creatOrderHour > 12){  //超过中午12点
                                        $('#limitAtextNo').addClass('alery').text('预约已满')
                                    }
                                }
                                var date = new Date(databox.serverTime);
                                var weekArr = ['周日','周一','周二','周三','周四','周五','周六'];
                                for(var m=0; m<4; m++){
                                    var listdan = {};
                                    var gDate = new Date(date.getTime() + Number(m)*24*60*60*1000);
                                    listdan.mounth = gDate.getMonth()+1;
                                    listdan.day = gDate.getDate();
                                    if(m==0){
                                        listdan.text='今天'
                                    }else {
                                        listdan.text=weekArr[gDate.getDay()]
                                    }
                                    $('.serverTime'+m).text(timeStamp2String(Number(databox.serverTime) + (m * 86400000), 2)+'['+listdan.text+']')
                                    Timeappdatan.push(timeStamp2String(Number(databox.serverTime) + (m * 86400000), 2))
                                }
                                //         console.log(Timeappdatan)
                            }
                        }
                    }
                }else {
                    quanhtml+=' <li data-text="'+anskn(deliverThird[deliverSupport[i]])+'" onclick="butionchan(this)">'+deliverThird[deliverSupport[i]]+'</li>'
                }
            }
        }
        $(".butionUl").html(quanhtml);
    }else {
        //没有支持的配送方式
        $(".butionUl").html('<p  style="color: #c62b26; line-height: 1.3">没有支持的配送方式</p>');
        // $('.weight').hide()
        $('#timHtml').hide()
    }
}
//配送方式操作
function butionchan(me) {
    if(!$(me).hasClass('cation')){
        $(me).addClass('cation').siblings().removeClass('cation')
        $(me).next().show()
        // alert($(me).next())
        freight($(me).attr('data-text'))
        Submission()
    }
}
//选择期望送达时间
function serviceExpect(eop) {
    defaultTime=true
    if(eop==1){
        for(var i=0; i<$('#timetablsit td').length; i++){
            var meHtml=$('#timetablsit td')[i]
            if($(meHtml).text()=='已选'){
                var nian=$(meHtml).attr('data-id')
                var zong=$(meHtml).attr('data-en')
                $('#pintime').html(Timeappdatan[nian]+' '+Minutedatan[zong])
                defaulData=Timeappdatan[nian]+' '+Minutedatan[zong]
            }
        }
        if($("input[name='morning']:checked").val()==2){
            $('#morningAfternoon').text($('#Tipsupper').text())
        }else {
            $('#morningAfternoon').text('')
        }
        closeNoLimit()
    }else {
        for(var i=0; i<$('#timetablsiton td').length; i++){
            var meHtml=$('#timetablsiton td')[i]
            if($(meHtml).text()=='已选'){
                var nian=$(meHtml).attr('data-id')
                var zong=$(meHtml).attr('data-en')
                $('#pintime').html(Timeappdatan[nian]+' '+'0:00-3:00')
                defaulData=Timeappdatan[nian]+' '+'0:00-3:00'
            }
        }
        closeAct()
    }
}
function modifyTagging() {
    if (databox.shippingAddressModel.areaLimitLine == 10) {  //限行
        for(var i=0; i<$('#timetablsiton td').length; i++){
            var meHtml=$('#timetablsiton td')[i]
            if($(meHtml).text()=='已选'){
                var nian=$(meHtml).attr('data-id')
                if(Timeappdatan[nian]==Timeappdatan[1]){
                    $('#xianxText').text('提示：请于12点前完成订单支付或确认')
                }else if(Timeappdatan[nian]==Timeappdatan[2]){
                    $('#xianxText').text('提示：请于次日12点前完成订单支付或确认')
                }else if(Timeappdatan[nian]==Timeappdatan[3]){
                    $('#xianxText').text('提示：请尽快完成订单支付或确认')
                }
            }
        }
    }else {
        for(var i=0; i<$('#limitAction td').length; i++){
            var meHtml=$('#limitAction td')[i]
            if($(meHtml).text()=='已选'){
                var nian=$(meHtml).attr('data-id')
                var zong=$(meHtml).attr('data-en')
                if(Timeappdatan[nian]==Timeappdatan[1]&&Minutedatan[zong]==Minutedatan[0]){
                    $('#limitedText').text('提示：请于12点前完成订单支付或确认')
                }else if(Timeappdatan[nian]==Timeappdatan[1]&&Minutedatan[zong]==Minutedatan[1]||Timeappdatan[nian]==Timeappdatan[1]&&Minutedatan[zong]==Minutedatan[2]){
                    $('#limitedText').text('提示：请于24点前完成订单支付或确认')
                }else if(Timeappdatan[nian]==Timeappdatan[2]||Timeappdatan[nian]==Timeappdatan[3]){
                    $('#limitedText').text('提示：请尽快完成订单支付或确认')
                }
                if(Minutedatan[zong]==Minutedatan[0]){
                    $('#Tipsupper').text('仅上午收货')
                    $('#Tipstime').text('8:00-12:00')
                }else if(Minutedatan[zong]==Minutedatan[1]){
                    $('#Tipsupper').text('仅下午收货')
                    $('#Tipstime').text('12:00-17:00')
                }else if(Minutedatan[zong]==Minutedatan[2]){
                    $('#Tipsupper').text('仅晚间收货')
                    $('#Tipstime').text('17:00-22:00')
                }
            }
        }
        if($('#Tipsupper').text()==''){
            var selects=document.getElementsByName("morning");
            for(var i=0; i<selects.length; i++){
                if(selects[i].value=="1") {
                    selects[i].checked= true;
                    break;
                }
            }
        }

    }

}
/*配送时间计算*/
var defaultTime=false//是否有选择时间
var defaulData=''//选中时间的值
function timeFun(logisticsMode) {
    if (logisticsMode == "private") {
        if(defaultTime){
            $('#pintime').html(defaulData)
            return false
        }else{
            $('#morningAfternoon').text('')
            if(databox.maxArrivalCycle==0){
                if (databox.shippingAddressModel.limitLine == 10){  //限行
                    // 限行
                    var creatOrderHour = timeStamp2String(databox.serverTime, 1);
                    if (creatOrderHour >= 0 && creatOrderHour <= 12){
                        var serverTime = timeStamp2String(Number(databox.serverTime) + (1 * 86400000), 2);
                        $('#pintime').html(serverTime + " 00:00-03:00")
                    } else {
                        var serverTime = timeStamp2String(Number(databox.serverTime) + (2 * 86400000), 2);
                        $('#pintime').html(serverTime + " 00:00-03:00")
                    }
                } else if (databox.shippingAddressModel.limitLine == 20){
                    var creatOrderHour = timeStamp2String(databox.serverTime, 1);
                    if (creatOrderHour >= 0 && creatOrderHour <= 12) {
                        var serverTime = timeStamp2String(Number(databox.serverTime) + 86400000, 2);
                        $('#pintime').html(serverTime + " 08:00-12:00")
                    } else {
                        var serverTime = timeStamp2String(Number(databox.serverTime) + 86400000, 2);
                        $('#pintime').html(serverTime + " 12:00-17:00")
                    }
                }
            }else{
                var len = Number(databox.maxArrivalCycle)+1;
                var serverTime = timeStamp2String(Number(databox.serverTime) + (86400000*len), 2);
                $('#pintime').html(serverTime)

            }
        }
    } else if(logisticsMode == "kd"){
        $('#pintime').html(databox.freight.kdDeliverTime)
    } else if(logisticsMode == "ky"){
        $('#pintime').html(databox.freight.kyDeliverTime )
        //1.2.0需要修改
    }else if(logisticsMode == "kyMy"){
        $('#pintime').html(databox.freight.kyMyDeliverTime )
    } else if(logisticsMode == "car"){
        $('#pintime').html(databox.freight.carDeliverTime)
    }
}
//快运内切换
function fastdata(myme) {
    var corer='kyMy'
    if(myme==1){
        corer='ky'
    }
    freight(corer)
    Submission()
}
//配送方式改变运费
function freight(me) {
    console.log(me)
    subdata.deliverWay=me
    Subsubdata.deliverWay=me
    var feeda=me+'Freight'
    // if(feeda=='kyMyFreight'){
    //     feeda='kyFreight'
    // }
    freightdata=databox.freight[feeda]
    $('#freight').html(freightdata)//运费
    for(var i=0;i<$('.butionUl>li').length; i++){
        var meHtml=$('.butionUl>li')[i]
        bootmonry()
        // console.log($(meHtml)[0].innerHTML)
        if(!$(meHtml).hasClass('cation')) {
            // subdata.deliverWay='car'
            console.log($(meHtml).attr('data-text'))
        }
    }
    if(me){
        timeFun(me)
    }
    $('#banlong').html(Number(databox.maxLength)/100)//最长边
    var total=(Number(databox.goodTotalVolume)/1000000).toFixed(2)
    if(total==0.00){
        $('#total').html('0.01')//总体积
    }else{
        $('#total').html(total)//总体积
    }
    $('#heavy').html(Number(databox.goodTotalWeight).toFixed(2))//最长边
}
// 指定价判断
function getSaleType(saleTypeCode) {
    switch (saleTypeCode){
        case 10:
            return "指定展示价"
            break;
        case 20:
            return "指定交易价"
            break;
        case 30:
            return "指定展示价和指定交易价"
            break;
        case 40:
            return "批发价"
            break;
        case 50:
            return "分销价"
            break;
        default:
            return ""
            break;
    }
}
//商品渲染
function commodity() {
    $(".goods_table").html('');
    var commHtml=''
    jQuery.each(databox.skuModelList, function(i, val) {
        var canHtml=''
        for(var e=0; e<databox.skuModelList[i].length;e++){
            var abnormal=''
            var danquan
            var textHtml='有货'
            var gongy= databox.abnormalProducts//异常商品
            if(gongy){
                for(var n=0; n<gongy.length; n++){
                    if(gongy[n].skuId==databox.skuModelList[i][e].skuId){
                        danquan=true
                        // if(gongy[n].code==70){
                        //     textHtml='价格调整'
                        // }else if (gongy[n].code==73){
                        //     textHtml='调整'
                        // }else {
                        //     textHtml='缺货'
                        // }
                    }else{
                        danquan=false
                    }
                    // alert(123)
                    if(danquan){
                        abnormal='marktd'
                        textHtml='无货'
                    }
                }
            }
            var topHtml=''
            if(e==0){
                topHtml='<td class="info"><span class="info_img"><img src=' + databox.skuModelList[i][e].productPic+ ' id="objskuId"></span><span class="info_text">'+databox.skuModelList[i][e].skuName+'</span></td>'
            }else{
                topHtml='<td class="info"></td>'
            }
            //指定价格不能改价
            var saleType=getSaleType(Number(databox.skuModelList[i][e].saleType))
            var inputShow='inputShow'
            if(databox.skuModelList[i][e].saleType==20||databox.skuModelList[i][e].saleType==30){
                inputShow=''
            }
            if(Facetoface){
                //询价单进入不需要spu集合
                canHtml+='<tr class="trHTml" data-spuId="'+databox.skuModelList[i][e].spuId+'" data-Number="'+databox.skuModelList[i][e].buyyerCount+'" data-mount="'+databox.skuModelList[i][e].salePrice+'" data-code="'+databox.skuModelList[i][e].skuCode+'" data-type="'+databox.skuModelList[i][e].adminChangePrice+'" data-name="'+databox.skuModelList[i][e].skuName+'">'
                    +'<td class="info"><span class="info_img"><img src=' + databox.skuModelList[i][e].productPic+ ' id="objskuId"></span><span class="info_text">'+databox.skuModelList[i][e].skuName+'</span></td>'
                    +'<td class="danGe diasnm'+abnormal+'"><span class="number" style="float: none">'+databox.skuModelList[i][e].specifications+'</span> X <span class="model">'+databox.skuModelList[i][e].buyyerCount+'</span></td>'
                    +'<td class="danGe '+abnormal+'">'+saleType+'</td>'
                    +'<td class="price '+abnormal+'">¥<input class="inputster '+inputShow+'" type="text" readonly="readonly" data-costPrice="'+databox.skuModelList[i][e].costPrice+'" oninput="Smallplan(this)"  onblur="likai(this)"  autocomplete="off" data-align="'+databox.skuModelList[i][e].salePrice+'" data-val="'+databox.skuModelList[i][e].srcSalePrice+'" value="'+databox.skuModelList[i][e].salePrice+'" id="inputshow" style="width: 65px;"/>&nbsp;&nbsp;&nbsp;'
                    +'<td class="shanShare"></td>'
                    +'<td data-yuan="'+Number(databox.skuModelList[i][e].salePrice*databox.skuModelList[i][e].buyyerCount).toFixed(2)+'" class="sub_price '+abnormal+'">¥<span>'+Number(databox.skuModelList[i][e].salePrice*databox.skuModelList[i][e].buyyerCount).toFixed(2)+'</span></td>'
                    +'<td class="operate  '+abnormal+' ">'+textHtml+'</td>'
                    +'<td class="hide '+abnormal+' ">" + obj.skuId + "</td>'
                    +'</tr>'
            }else {
                canHtml+='<tr class="trHTml" data-spuId="'+databox.skuModelList[i][e].spuId+'" data-Number="'+databox.skuModelList[i][e].buyyerCount+'" data-mount="'+databox.skuModelList[i][e].salePrice+'" data-code="'+databox.skuModelList[i][e].skuCode+'" data-type="'+databox.skuModelList[i][e].adminChangePrice+'" data-name="'+databox.skuModelList[i][e].skuName+'">'
                    +''+topHtml+''
                    +'<td class="danGe diasnm '+abnormal+'"><span class="number" style="float: none">'+databox.skuModelList[i][e].specifications+'</span> X <span class="model">'+databox.skuModelList[i][e].buyyerCount+'</span></td>'
                    +'<td class="danGe '+abnormal+'">'+saleType+'</td>'
                    +'<td class="price '+abnormal+'">¥<input class="inputster '+inputShow+'" type="text" readonly="readonly" data-costPrice="'+databox.skuModelList[i][e].costPrice+'" oninput="Smallplan(this)"  onblur="likai(this)"  autocomplete="off" data-align="'+databox.skuModelList[i][e].salePrice+'" data-val="'+databox.skuModelList[i][e].srcSalePrice+'" value="'+databox.skuModelList[i][e].salePrice+'" id="inputshow" style="width: 65px;"/>&nbsp;&nbsp;&nbsp;'
                    +'<td class="shanShare"></td>'
                    +'<td data-yuan="'+Number(databox.skuModelList[i][e].salePrice*databox.skuModelList[i][e].buyyerCount).toFixed(2)+'" class="plan sub_price '+abnormal+'">¥<span>'+Number(databox.skuModelList[i][e].salePrice*databox.skuModelList[i][e].buyyerCount).toFixed(2)+'</span></td>'
                    +'<td class="operate  '+abnormal+' ">'+textHtml+'</td>'
                    +'<td class="hide '+abnormal+' ">" + obj.skuId + "</td>'
                    +'</tr>'
            }
        }
        commHtml+='<div>'+canHtml+'</div>'
        //运费备注刷新
        if(databox.modifiyFreightReason!=undefined&&databox.modifiyFreightReason!=''){
            $('#Remarkslist').show()
            $('#yunfeiRemarks').html(databox.modifiyFreightReason)
        }
    });
    $(".goods_table").html(commHtml);
    //初始是否分摊
    if(databox.freightSeparate==20){
        yunSharefun(20)
        $('.shanShare').show()
    }else {
        $('.shanShare').hide()
    }
    if ($('.goods_table >tr').length > Number(3)) {
        $('.goods_table').find('tr:gt(2)').hide();
        $('#many').show()
        $('#little').hide()
        // alert(321)
    } else {
        $('.goods_table').find('tr').show();
        $('#little').hide()
        $('#many').hide()
        // alert(123)
    }
    bootmonry()
}
function moreProduct(lsit) {
    if(lsit==1){
        $('.goods_table').find('tr').show();
        $('#little').show()
        $('#many').hide()
    }else {
        $('.goods_table').find('tr:gt(2)').hide();
        $('#many').show()
        $('#little').hide()
    }
}
//运费分摊
function yunSharefun(dan) {
    if(dan==10){
        //运费单开
        $('.shanShare').hide()
        bootmonry(undefined,2)
    }else {
        //运费分摊
        $('.shanShare').show()
        bootmonry(undefined,2)
        for (var i = 0; i < $('.goods_table >tr').length; i++) {
            var meHtml=$('.goods_table >tr')[i]
            var Price=$(meHtml).find('.price ').find('input').val()//当前商品价格
            var model=$(meHtml).find('.danGe').find('.model').text()//当前购买数量
            console.log(freightdata)
            console.log(Totalcommodity)
            var meconter=(Number(freightdata)/Number(Totalcommodity))*Number(Price)*Number(model)
            $(meHtml).find('.shanShare ').text((meconter).toFixed(2))
        }

    }
}
var snkonOrice=false
/*改价*/
function ChangePrice(me) {
    //初始化商品改价备注
    $('#chanGeremar').removeClass('chanGeremarcss')
    $('#chanGeremar').val('')
    console.log(databox.couponChoosen)
    if(databox.couponChoosen==undefined){
        if(pricedata){
            // $('#chanGeremar').show()//商品改价备注
            pricedata=false
            $(me).val('取消改价')
            //使优惠券不可点击
            Discount=false
            //button
            // $(".ButtonTrue").show()
            $('.inputShow').removeAttr("readonly");
            $('.inputShow').addClass('addinputShow')
        }else {
            $('#chanGeremar').hide()//商品改价备注
            commodity()//商品渲染
            pricedata=true
            $(me).val('商品改价')
            Discount=true
            snkonOrice=false
        }
    }else {
        console.log(couponModel)
        layer.msg('使用优惠券不能改价，请取消优惠券勾选', {icon: 5, time: 2000});
    }
}
//根据改价改变小计
function Smallplan(me) {
    var meval=$(me).val()
    // if (/^\d+(?=\.{0,1}\d+$|$)/.test(meval)) {
    var umber=$(me).parent().parent().find('.diasnm').find('.model').text()
    meval = meval.replace(/[^\d.]/g,"");
    // meval=Number(meval).toFixed(2)
    // console.log(meval)
    if (/^\d+(?=\.{0,1}\d+$|$)/.test(meval)) {
        if (/^\d+\.?\d{0,2}$/.test(meval)) {
            meval = meval;
        } else {
            meval = meval.substring(0, meval.length-1);
        }
    } else {
        meval = meval.replace(/[^\d.]+/, '')
    }
    console.log(meval)
    $(me).val(meval)
    console.log($(me).parent().parent().find('.plan').find('span').text())
    console.log(umber)
    $(me).parent().parent().find('.plan').find('span').text(Number(umber*Number(meval)).toFixed(2))
    if(meval==$(me).attr('data-val')){
        // alert(123)
        $(me).parent().parent().attr('data-type','')
        checkPrice()
    }else {
        $(me).parent().parent().attr('data-type',10)
        checkPrice()
    }
    bootmonry(undefined,2)
}
//改价提示
function likai(me) {
    var state=false
    var gaiText=''
    var meval=$(me).val()
    var meyanj=$(me).attr('data-val')
    var costPrice=$(me).attr('data-costPrice')//成本价格
    var numb=Number($(me).attr('data-val'))*0.3
    var top=Number($(me).attr('data-val'))+numb
    var lower=Number($(me).attr('data-val'))-numb
    console.log('上浮上线'+top)
    console.log('下浮上线'+lower)
    console.log('成本价'+costPrice)
    if(meval==''){
        $.Huimodalalert("请填写价格", 2000);
        $(me).val($(me).attr('data-align'))
        $(me).parent().next().find('span').text( $(me).attr('data-align'))
        $(me).parent().parent().attr('data-type','')
        checkPrice()
        return false
    }
    if(meval>top){
        state=true
        gaiText='价格上幅超30%，您确认吗'
        fication(2,meyanj)
    }
    if(meval<lower){
        state=true
        gaiText='价格下幅超30%，您确认吗'
        fication(2,meyanj)
    }
    if(meval<Number(costPrice)){
        state=true
        gaiText='价格低于成本价，您确定改价吗'
        fication(2,meyanj)
    }
    if(meval<Number(costPrice)&&meval<lower){
        fication(1,meyanj)
    }
    function fication(mak,yan) {
        if(mak==1){
            layer.confirm('价格下幅超30%，您确认吗', {
                btn: ['确定','取消'] //按钮
            }, function(){
                layer.confirm('价格低于成本价，您确定改价吗', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    layer.msg('改价成功', {icon: 6,time:1000});
                    $(me).parent().parent().attr('data-type','10')
                    $(me).attr('data-align',meval)
                    bootmonry(undefined,2)
                    checkPrice()
                }, function(){
                    if($(me).attr('data-align')==yan){
                        $(me).parent().parent().attr('data-type','')
                    }
                    $(me).val($(me).attr('data-align'))
                    $(me).parent().next().find('span').text( $(me).attr('data-align'))
                    // $(me).parent().parent().attr('data-type','')
                    checkPrice()
                    bootmonry(undefined,2)
                })
            }, function(){
                if($(me).attr('data-align')==yan){
                    $(me).parent().parent().attr('data-type','')
                }
                $(me).val($(me).attr('data-align'))
                $(me).parent().next().find('span').text( $(me).attr('data-align'))
                // $(me).parent().parent().attr('data-type','')
                checkPrice()
                bootmonry(undefined,2)
            })
        }else {
            layer.confirm(gaiText, {
                btn: ['确定','取消'] //按钮465
            }, function(){
                layer.msg('改价成功', {icon: 6,time:1000});
                $(me).parent().parent().attr('data-type','10')
                $(me).attr('data-align',meval)
                bootmonry(undefined,2)
                checkPrice()
            }, function(){
                if($(me).attr('data-align')==yan){
                    $(me).parent().parent().attr('data-type','')
                }
                $(me).val($(me).attr('data-align'))
                $(me).parent().next().find('span').text( $(me).attr('data-align'))
                // $(me).parent().parent().attr('data-type','')
                checkPrice()
                bootmonry(undefined,2)
            })
        }
    }
}
//商品改价备注标红取消
function Standardred(me) {
    if($(me).val()==''){
        $('#chanGeremar').addClass('chanGeremarcss')
    }else {
        $('#chanGeremar').removeClass('chanGeremarcss')
    }
}
//监听订单商品是否改价若改价 出现改价备注
function canlonXmd() {
    if(snkonOrice){
        $('#chanGeremar').removeClass('chanGeremarcss')
        // $('#chanGeremar').val('')
        $('#chanGeremar').show()
    }else {
        $('#chanGeremar').hide()
    }
}
//校验当前商品是否有改价
function checkPrice () {
    yunSharefun($("#yunShare").val())
    comdata()
    console.log(nkm.skuModelList)
    // var sele=''
    var checkedArr=[]
    for(var i=0; i<nkm.skuModelList.length; i++){
        //是否有改价商品
        if(nkm.skuModelList[i].adminChangePrice==10){
            checkedArr.push(false)
        }else {
            checkedArr.push(true)
        }
    }
    if(checkedArr.indexOf(false)==-1){
        console.log('没有改价商品')
        snkonOrice=false
    }else {
        console.log('有改价商品')
        snkonOrice=true
    }
    canlonXmd()
}
/*运费弹框显示事件*/
function Modifyshipping(){
    if(freightdata==0){
        layer.msg('无法修改运费', {icon: 5, time: 2000});
        return false
    }
    if(databox.couponChoosen==undefined){
        $(".before").html("¥ "+$("#yunfei").html());
        $("#yunfei-beforeChange").html($("#yunfei").html());
        $("#modal-demo").modal("show");
    }else{
        layer.msg('使用优惠券不能改价，请取消优惠券勾选', {icon: 5, time: 2000});
    }
}
/* 控制修改运费最多输入到小数点后两位 */
function checknum(obj) {
    if (/^\d+(?=\.{0,1}\d+$|$)/.test(obj.value)) {
        if (/^\d+\.?\d{0,2}$/.test(obj.value)) {
            obj.value = obj.value;
        } else {
            obj.value = obj.value.substring(0, obj.value.length-1);
        }
    } else {
        obj.value = obj.value.replace(/[^\d.]+/, '')
    }
}
function sureChangeFare() {
    if ($(".after").val() == "") {
        $.Huimodalalert("请输入运费", 2000);
        return false;
    }
    if ($(".change_freight_comment").val() == "") {
        $.Huimodalalert("请输入修改原因", 2000);
        return false;
    }
    $("#afterFare-remark").html($("#changeRemark").val());
    modifiyFreightReason=$("#changeRemark").val()
    //是显示修改运费备注
    $('#Remarkslist').show()
    $('#yunfeiRemarks').html(modifiyFreightReason)
    freightdata=$(".after").val()
    bootmonry(undefined,2)
    $('#freight').text(freightdata)
    Discount=false
    $("#modal-demo").modal("hide");
    $(".after").val("");
    $("#changeRemark").val("");
    freightIsChange = 10;
}
function closeChangeFare() {
    $(".after").val("");
    $("#changeRemark").val("");
}
//商品后初始订单下方总数据
var zongfreig
var sentencenk=[]
function bootmonry(youhui,shan) {
    sentencenk=[]
    if(databox.adminChangeFreight!=undefined){
        freightdata=databox.adminChangeFreight
        Discount=false
    }
    $('#yunfei').html(Number(freightdata).toFixed(2))//运费
    var TotalNum=databox.skuTotalNum
    $('#total_count').html(Number(TotalNum).toFixed(0))//总共商品数量
    if(shan==2){
        var totaldan=0
        for(var i=0; i<$('.goods_table >tr').length; i++){
            var dangHtml=$('.goods_table >tr')[i]
            var mount=$(dangHtml).find('.sub_price').find('span').text()
            sentencenk.push(mount)
            totaldan=Number(totaldan)+Number(mount)
        }
        Totalcommodity=totaldan
        $('#goodTotalMoney').html(Number(Totalcommodity).toFixed(2))//商品总额
        console.log(totaldan)
    }else {
        Totalcommodity=databox.goodTotalMoney
        $('#goodTotalMoney').html(Number(Totalcommodity).toFixed(2))//商品总额
    }
    var youhuijuan=coupon
    var remission=yunupn
    if(youhuijuan>Number($('#goodTotalMoney').html())){
        youhuijuan=Number($('#goodTotalMoney').html())
    }
    if(remission>Number( $('#yunfei').html())){
        remission=Number( $('#yunfei').html())
    }
    var lsin=false
    if($("#yunShare").val()!=10){
        $('#yunfei').html(Number(0).toFixed(2))//运费
        $('#goodTotalMoney').html(Number(Number(Totalcommodity)+Number(freightdata)).toFixed(2))//商品总额
        lsin=true
    }else {
        $('#yunfei').html(Number(freightdata).toFixed(2))//运费
        if(lsin){
            $('#goodTotalMoney').html(Number(Number(Totalcommodity)-Number(freightdata)).toFixed(2))//商品总额
            lsin=false
        }
    }
    $('#youhuijuan').html(Number(youhuijuan).toFixed(2))
    $('#remission').html(Number(remission).toFixed(2))
    zongfreig=freightdata-remission
    var total=Number($('#goodTotalMoney').html())+Number( $('#yunfei').html())-youhuijuan-remission
    $("#zongjine").html(Number(total).toFixed(2))//应付总额
}
//获取当前商品数据
function comdata() {
    var shunconk=[]
    for(var i=0; i<$('.goods_table >tr').length; i++){
        var nnm={}
        var dangHtml=$('.goods_table >tr')[i]
        var mount=$(dangHtml).find('.price').find('input').val()
        var code=$(dangHtml).attr('data-code')
        var type=$(dangHtml).attr('data-type')
        var nmber=$(dangHtml).attr('data-Number')
        var spuId=$(dangHtml).attr('data-spuId')
        if(spuId==0){
            spuId=1
        }else {
            spuId=null
        }
        if(type==undefined||type==null){
            type=''
        }
        // console.log(mount)
        var name=$(dangHtml).attr('data-name')
        // console.log($(dangHtml).attr('data-mount'))
        nnm['salePrice']=mount
        nnm['skuCode']=code
        nnm['adminChangePrice']=type
        nnm['skuName']=name
        nnm['buyyerCount']=nmber
        nnm['tempPurchase']=spuId
        shunconk.push(nnm)
    }
    // console.log(shunconk)
    nkm.skuModelList=shunconk
}
function Submission(tepe) {
    var openFlagdata=''
    comdata()
    for(var i=0; i<$('#methodHtml >span').length; i++){
        var canHTml=$('#methodHtml >span')[i]
        if($(canHTml).hasClass('Selectexnt')){
            subdata.payModelChoosen.payName=$(canHTml).attr('data-text')
            subdata.payModelChoosen.payType=$(canHTml).attr('data-id')
        }
        if(subdata.payModelChoosen.payName=='账期支付'){
            openFlag=null
        }
    }
    // freight()
    if(tepe==1) {
        //提交订单
        //判断商品中是否有金额为0的商品
        console.log(sentencenk)
        for (var k = 0; k < sentencenk.length; k++) {
            if (Number(sentencenk[k]) <= 0) {
                $.Huimodalalert("单个商品价格不能为0", 2000);
                return false
            }
        }
        Subsubdata.couponModel = couponModels//优惠劵信息集合
        for (var i = 0; i < $('#methodHtml >span').length; i++) {
            var canHTml = $('#methodHtml >span')[i]
            if ($(canHTml).hasClass('Selectexnt')) {
                console.log()
                Subsubdata.payModel.payName = $(canHTml).attr('data-text')
                Subsubdata.payModel.payType = $(canHTml).attr('data-id')
                if (paymentState) {
                    if($(canHTml).attr('data-text')=='货到付款'){
                        Subsubdata.payModel.paySubType = $("input[name='ban']:checked").val()//货到付款
                    }else {
                        Subsubdata.payModel.paySubType=null
                    }//货到付款
                }
            }
        }
        Subsubdata.codeUuid = databox.codeUuid//
        // Subsubdata.finalTotalAmount=$("#zongjine").html()//商品金额（没有任何优惠）
        Subsubdata.freight = freightdata//运费
        Subsubdata.goodTotalMoney = databox.goodTotalMoney//不需要保留两位小数
        Subsubdata.goodTotalNum = databox.skuTotalNum
        Subsubdata.goodTotalWeight = databox.goodTotalWeight
        // alert(snkonOrice)
        if (snkonOrice) {
            if ($('#chanGeremar').val() == ''){
                $.Huimodalalert("请填写商品改价备注", 2000);
                $('#chanGeremar').addClass('chanGeremarcss')
                return false
            }
            Subsubdata.changePriceRemark = $('#chanGeremar').val()
        }
        if(openFlag){
            openFlagdata=20
        }else {
            openFlagdata=10
        }
        Subsubdata.invoiceFlag=openFlagdata//发票
        if (databox.shippingAddressModel.areaLimitLine){
            Subsubdata.limitLine=databox.shippingAddressModel.areaLimitLine
        }
        Subsubdata.loginAccount=datalist.customerLoginAccount
        // Subsubdata.payMoney=$("#zongjine").html()//支付总结金额
        if($("#zongjine").html()<0){
            $.Huimodalalert("商品总额有误", 2000);
            return false
        }
        if(Number($("#goodTotalMoney").html())==0){
            $.Huimodalalert("商品价格有误", 2000);
            return false
        }
        Subsubdata.qualityFileRequired=$("#zzNeed").val()//是否需要资质 10需要  20不需要
        Subsubdata.receiveOnlyAt=0//期望送到时间
        if($('#morning').val()==1){
            Subsubdata.receiveOnlyAt=$('#morning').val()
        }
        Subsubdata.separateShippingFee=$("#yunShare").val();// 10是运费单开，20否
        var canlsien=$('#pintime').text()
        var bootsud=''
        var topsud=''
        var nmensud=''
        // canlsien=canlsien.replace(/[^0-9]/ig,'-')
        // canlsien = canlsien.substring(0, canlsien.length - 1);
        bootsud= canlsien.substring(0, 10);
        bootsud=bootsud.replace(/[^0-9]/ig,'-')
        topsud= canlsien.substring(12, 17);
        if(topsud==''){
            topsud='00:00'
        }
        nmensud= canlsien.substring(18, 25);
        if(nmensud==''){
            nmensud='23:59'
        }
        Subsubdata.wannaArrivedAtBegin=bootsud+' '+topsud+":00"
        Subsubdata.wannaArrivedAtEnd=bootsud+' '+nmensud+":59"
        Subsubdata.dispatchBillModel=nkm//重新创建商品信息
        // delete  subdata.skuModelList//删除保存对象里的商品信息集合
        Subsubdata.shippingAddress=chooseAddressObj//地址
        Subsubdata.remarks=$('#remarks').val()//订单备注
        if (invoiceType==1){
            invoiceType=20
        }else {
            invoiceType=10
        }
        Subsubdata.invoiceType=invoiceType,//发票类型：10-增值税；20-普税
            Subsubdata.invoiceTitle=invoiceInfo.title////发票抬头/单位名称
        Subsubdata.taxpayerIdentifyNum=invoiceInfo.code// 纳税人识别号
        Subsubdata.registerAddress=invoiceInfo.address  //注册地址
        Subsubdata.registerPhone=invoiceInfo.phone;  //注册电话
        Subsubdata.openBank=invoiceInfo.bank;  //开户银行
        Subsubdata.bankAccount=invoiceInfo.bankAccount;  //银行账户
        Subsubdata.fileCopies= $("#zzNum").val()//资质数量
        Subsubdata.originalFile=$("input[name='zzyy']:checked").val()//是否需要原件 10是 20否
        if(freightIsChange==10){
            Subsubdata.adminChangeFreight=freightdata//判断运费是否修改
        }
        // alert(modifiyFreightReason)
        Subsubdata.modifiyFreightReason=modifiyFreightReason//修改运费备注
        if(customerInfo.inquiryWarehouseId!=''){
            // alert($("input[name='conernt']:checked").val())
            console.log($("input[name='conernt']:checked").val())
            if(Facetoface){
                if($("input[name='conernt']:checked").val()==undefined){
                    $.Huimodalalert("请选择配送方式", 2000);
                    return false
                }
            }
            Subsubdata.deliverWaySecondary=$("input[name='conernt']:checked").val()//配送方式
            Subsubdata.inquiryWarehouseId=customerInfo.inquiryWarehouseId
        }
        Subsubdata.freight=freightdata
        // alert(zongfreig)
        var quzhi=JSON.parse(web.readCookie("loginData"))
        Subsubdata.roleName=quzhi.user.name//当前操作人
        Subsubdata.roleId=quzhi.user.user_ID//当前操作人 id
        Subsubdata.tempPurchase=tempPurchase//临采标识
        console.log(Subsubdata)
        $("#commitlsit").addClass('prohibitocnk')
        web.doAjax(root.replaceInter.submitTrade, 'post',Subsubdata, function (data) {
            $("#commitlsit").removeClass('prohibitocnk')
            if(data.errorCode==0){
                layer.msg('提交成功', {icon: 6, time: 2000});
                var index = layer.open({
                    type: 2,
                    title: "下单成功",
                    closeBtn: 0,
                    content: "creatSuccess.html?orderId=" + data.orderId
                });
                layer.full(index);
                return false
            }if(data.errorCode==61){
                Submission()
            }else{
                layer.msg(data.errorMessage, {icon: 5, time: 2000});
            }
        },1)
    }else{
        if (chooseAddressObj){
            chooseAddressObj==null
        }
        if(freightIsChange==10){
            subdata.adminChangeFreight=freightdata//判断运费是否修改
        }
        subdata.freightSeparate=$("#yunShare").val();// 10是运费单开，20否
        subdata.modifiyFreightReason=modifiyFreightReason//修改运费备注
        subdata.shippingAddressModel=chooseAddressObj//地址信息集合
        subdata.couponChoosen=couponModel//优惠劵信息集合
        if(customerInfo.inquiryWarehouseId!=''){
            // alert($("input[name='conernt']:checked").val())
            subdata.deliverWaySecondary=$("input[name='conernt']:checked").val()//配送方式
            subdata.inquiryWarehouseId=customerInfo.inquiryWarehouseId
        }
        web.doAjax(root.replaceInter.confirm, 'post',subdata, function (data) {
            if(data.errorCode==0){

            }else if(data.errorCode==61){
                $("#noStock").modal("show");
            }else {
                if(data.abnormalProducts!=''||data.abnormalProducts!=undefined){
                    $.Huimodalalert("商品有误请返回修改商品", 2000);
                }else {
                    $.Huimodalalert(data.tip, 2000);
                }
            }
            databox=data;
            addressInit(databox.shoppingAddList)//地址
            method(databox.payModelList)//支付方式
            Distribution()
            commodity()//商品渲染
            renderCoupon()//优惠券
            pricedata=true
            Discount=true
            $('#chanGeremar').hide()
            $('#changeprice').val('商品改价')
        },1)
    }
}
//订单提交
function commit() {
    Submission(1)
}



